from src.utils.config import logger
from src.utils.core import Block, Context
from src.utils.db_processor import mysql_trader
from src.utils.db_processor import presto_processor
import pandas as pd
import numpy as np
import datetime
import math


class GLOBALBlock(Block):

    def __init__(self, control_sql='''
            SELECT * FROM abtrader.price_adjustment_strategy_global_conf
            where category_name in
            (SELECT distinct category_name FROM price_adjustment_strategy_detail where enabled=1 and status=1);
            '''):

        self.control_sql = control_sql
        self.mysql_trader = mysql_trader
        self.gp = presto_processor

    def process(self, data):

        df_control = self.mysql_trader.load_sql(self.control_sql)
        if len(df_control) > 0:
            logger.info("global control ！！！")

            df_supply = self.gp.load_sql(
                '''
                    select 
                      a.product_id,
                      a.product_name,
                      a.product_brand_name,
                      a.product_category_parent_id as category_id,
                      a.product_category_parent_name as category_name,
                      coalesce(g.系数,0) 提价系数,
                      coalesce(g.系数,0)-coalesce(h.系数,0) 昨日系数变动幅度,
                      coalesce(h.系数,0)-coalesce(k.系数,0) 前日系数变动幅度,
                      coalesce(h.系数,0) T2提价系数,
                      coalesce(k.系数,0) T3提价系数
                    from
                    (
                      select
                      *
                      from dim.dim_product
                      where product_category_parent_id in ('1','6','5') and product_id_status_name='启用'
                    ) a
                    left join
                    (	  		-- 提价系数
                                select
                                    distinct product_id,product_name,wk_price_adjustment_ratio as 系数
                                from
                                    rpt.rpt_platform_automatic_adjustment_price_detail
                                where quotation_document_begin_date=CURRENT_DATE-1
                    ) g           
                    on a.product_id=g.product_id and a.product_name=g.product_name
                    left join
                    (	  		-- 昨日提价系数
                                select
                                    distinct product_id,product_name,wk_price_adjustment_ratio as 系数
                                from
                                    rpt.rpt_platform_automatic_adjustment_price_detail
                                where quotation_document_begin_date=CURRENT_DATE-2
                    ) h           
                    on a.product_id=h.product_id and a.product_name=h.product_name
                    left join
                    (	  		-- 前日提价系数
                                select
                                    distinct product_id,product_name,wk_price_adjustment_ratio as 系数
                                from
                                    rpt.rpt_platform_automatic_adjustment_price_detail
                                where quotation_document_begin_date=CURRENT_DATE-3
                    ) k           
                    on a.product_id=k.product_id and a.product_name=k.product_name;
            ''')

            logger.info("before merge supply count:\n{0}".format(df_supply.count()))
            logger.info("before merge data count:\n{0}".format(data.count()))

            # data = pd.merge(data, df_supply, how='left', on=['product_id'])

            data = pd.merge(df_supply, data, how='left', on=['product_id'])
            data['ratio'][(~data['提价系数'].isnull()) & (data['ratio'].isnull())] = \
                data['提价系数'][(~data['提价系数'].isnull()) & (data['ratio'].isnull())]
            data = data[(~data['ratio'].isnull())].reset_index()

            print(data.info())
            print(data['ratio'].unique())
            data['ratio'] = data['ratio'].astype(np.float64)
            print(data.info())
            print(data['ratio'].unique())

            data['ratio'] = data['ratio'].apply(lambda x: math.ceil(x['ratio'] * 100) / 100)

            data['control'] = ""
            data['flag'] = 0

            logger.info("after merge data count:\n{0}".format(data.count()))

            for index, control in df_control.iterrows():

                data['系数变动幅度'] = data['ratio'] - data['提价系数']

                # 品类名称
                category_name = control['category_name']
                # if category_name == "手机":
                #     data['flag'][data['category_name'] == category_name] = 1
                # if category_name == "平板电脑":
                #     data['flag'][data['category_name'] == category_name] = 1
                # if category_name == "笔记本":
                #     data['flag'][data['category_name'] == category_name] = 1

                data['flag'][data['category_name'] == category_name] = 1
                logger.info(
                    "data flag category_name:{0} count:\n{1}".format(category_name, data[data['flag'] == 1].count()))

                # 连续涨价天数
                price_incr_days = control['price_incr_days']
                if price_incr_days == 2:
                    logger.info("\nglobal conf_id:{0} category_name:{1} price_incr_days:{2}".
                                format(control['id'], category_name, price_incr_days))

                    data['control'][(data['category_name'] == category_name) &
                                    (data['系数变动幅度'] >= 0) & (data['昨日系数变动幅度'] > 0)] += "+2 "
                    data['ratio'][(data['category_name'] == category_name) &
                                  (data['系数变动幅度'] >= 0) & (data['昨日系数变动幅度'] > 0)] = \
                        data['提价系数'][(data['category_name'] == category_name) &
                                     (data['系数变动幅度'] >= 0) & (data['昨日系数变动幅度'] > 0)]

                elif price_incr_days == 3:
                    logger.info("\nglobal conf_id:{0} category_name:{1} price_incr_days:{2}".
                                format(control['id'], category_name, price_incr_days))

                    data['control'][(data['category_name'] == category_name) &
                                    (data['系数变动幅度'] >= 0) & ((data['昨日系数变动幅度'] > 0) | (data['前日系数变动幅度'] > 0))] += "+3 "
                    data['ratio'][(data['category_name'] == category_name) &
                                  (data['系数变动幅度'] >= 0) & ((data['昨日系数变动幅度'] > 0) | (data['前日系数变动幅度'] > 0))] = \
                        data['提价系数'][(data['category_name'] == category_name) &
                                     (data['系数变动幅度'] >= 0) & ((data['昨日系数变动幅度'] > 0) | (data['前日系数变动幅度'] > 0))]
                else:
                    logger.warn("\nglobal conf_id:{0} category_name:{1} price_incr_days:{2}".
                                format(control['id'], category_name, price_incr_days))

                # 连续降价天数
                price_cut_days = control['price_cut_days']
                if price_cut_days == 2:
                    logger.info("\nglobal conf_id:{0} category_name:{1} price_cut_days:{2}".
                                format(control['id'], category_name, price_cut_days))

                    data['control'][(data['category_name'] == category_name) &
                                    (data['系数变动幅度'] < 0) & (data['昨日系数变动幅度'] < 0)] += "-2 "
                    data['ratio'][(data['category_name'] == category_name) &
                                  (data['系数变动幅度'] < 0) & (data['昨日系数变动幅度'] < 0)] = \
                        data['提价系数'][(data['category_name'] == category_name) &
                                     (data['系数变动幅度'] < 0) & (data['昨日系数变动幅度'] < 0)]

                if price_cut_days == 3:
                    logger.info("\nglobal conf_id:{0} category_name:{1} price_cut_days:{2}".
                                format(control['id'], category_name, price_cut_days))

                    data['control'][(data['category_name'] == category_name) &
                                    (data['系数变动幅度'] < 0) & ((data['昨日系数变动幅度'] < 0) | (data['前日系数变动幅度'] < 0))] += "-3 "
                    data['ratio'][(data['category_name'] == category_name) &
                                  (data['系数变动幅度'] < 0) & ((data['昨日系数变动幅度'] < 0) | (data['前日系数变动幅度'] < 0))] = \
                        data['提价系数'][(data['category_name'] == category_name) &
                                     (data['系数变动幅度'] < 0) & ((data['昨日系数变动幅度'] < 0) | (data['前日系数变动幅度'] < 0))]
                else:
                    logger.warn("\nglobal conf_id:{0} category_name:{1} price_cut_days:{2}".
                                format(control['id'], category_name, price_cut_days))
                # 涨价阈值
                price_incr_threshold = control['price_incr_threshold']
                logger.warn("\nglobal conf_id:{0} category_name:{1} price_incr_threshold:{2}".
                            format(control['id'], category_name, price_incr_threshold))

                data['control'][(data['category_name'] == category_name) &
                                (data['ratio'] > price_incr_threshold)] += "max:" + str(price_incr_threshold) + " "
                data['ratio'][(data['category_name'] == category_name) &
                              (data['ratio'] > price_incr_threshold)] = price_incr_threshold

                # 降价阈值
                price_cut_threshold = control['price_cut_threshold']
                logger.warn("\nglobal conf_id:{0} category_name:{1} price_cut_threshold:{2}".
                            format(control['id'], category_name, price_cut_threshold))

                data['control'][(data['category_name'] == category_name) &
                                (data['ratio'] < price_cut_threshold)] = "min:" + str(price_cut_threshold) + " "
                data['ratio'][(data['category_name'] == category_name) &
                              (data['ratio'] < price_cut_threshold)] = price_cut_threshold

        logger.info("after control count:\n{0}".format(data.count()))

        data = data[data['flag'] == 1]
        logger.info("flag=1 count:\n{0}".format(data.count()))

        data = data[data['ratio'] > 0]
        logger.info("ratio>0 count:\n{0}".format(data.count()))

        data['ratio_bi'] = data['ratio']
        data['ratio_yuan'] = data['ratio']
        data['date'] = datetime.date.today()

        df_ratio = data[['plan_id', 'plan_name', 'control',
                         'date', 'category_id', 'category_name',
                         'product_brand_name',
                         'product_id', 'product_name',
                         'ratio_bi', 'ratio_yuan']]
        return df_ratio

    def run(self, context=Context()):
        logger.info("{0}:{1}".format(self.__class__.__name__, self.control_sql))

        context.setData(self.process(context.getData()))

        logger.info("\nContext Data\n{0}".format(context.getData()))
